//
//  CalculatorLogic.swift
//  JonCalculator
//
//  Created by shiyanjun on 2023/1/15.
//

import Foundation

struct CalculatorLogic {
    private var number: Double?
    // 使用元组存储运行中的数字和运算符
    private var intermediatecalculation: (n1: Double, calcMethod: String)?
    
    mutating func setNumber(_ number: Double) {
        self.number = number
    }
    
    mutating func calculate(symbol: String) -> Double? {
        if let n = number {
            switch symbol {
            case "+/-":
                return n * -1
            case "AC":
                return 0
            case "%":
                return n * 0.01
            case "=":
                return performTwoNumCalculator(n2: n)
            default:
                intermediatecalculation = (n1: n, calcMethod: symbol)
            }
        }
        return nil
    }
    
    private func performTwoNumCalculator(n2: Double) -> Double? {
        if let n1 = intermediatecalculation?.n1,
           let operation = intermediatecalculation?.calcMethod {
            switch operation {
            case "+":
                return n1 + n2
            case "-":
                return n1 - n2
            case "x":
                return n1 * n2
            case "/":
                return n1 / n2
            default:
                fatalError("输入的运算符有误")
            }
        }
        return nil
    }
}
